package com.example.makerspace.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.makerspace.domain.NewsDO;
import com.example.makerspace.dto.NewsDTO;
import com.example.makerspace.mapper.NewsMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Component
public class NewsDAO extends BaseDAO<NewsDO>{

    public final static String TITLE = "title";
    public final static String SHOW_TIME = "show_time";

    @Resource
    private NewsMapper newsMapper;

    @PostConstruct
    public void init(){
        this.mapper = newsMapper;
    }

    public NewsDO selectByNewsTitle(NewsDTO newsDTO){
        return newsMapper.selectOne(new QueryWrapper<NewsDO>().eq(TITLE, newsDTO.getTitle()));
    }

    public List<NewsDO> selectLatest(Integer num){
        return newsMapper.selectList(new QueryWrapper<NewsDO>().orderByDesc(SHOW_TIME).last("limit " + num));
    }


    public IPage<NewsDO> selectByPage(Page<NewsDO> page, String name) {
        LambdaQueryWrapper<NewsDO> qw = new LambdaQueryWrapper<NewsDO>()
                .like(StringUtils.isNotEmpty(name),NewsDO::getTitle,name).or()
                .like(StringUtils.isNotEmpty(name),NewsDO::getContent,name);
        return  mapper.selectPage(page,qw);
    }
}
